﻿using CommunityToolkit.Mvvm.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using SSHTool.Service;
using SSHTool.Util;
using SSHTool.View;
using SSHTool.ViewModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace SSHTool
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private static IServiceCollection services;
        private static IServiceProvider serviceProvider;
        private Mutex mutex;

        protected override void OnStartup(StartupEventArgs e)
        {
            string name = Assembly.GetExecutingAssembly().GetName().Name;
            mutex = new Mutex(true, name, out bool flag);
            if (flag)
            {
                ConfigureServices();

                //RegisterErrorHandler();
            }
            else
            {
                var p = ProcessUtil.GetCurrentProcess();
                Win32Util.ShowWindowAsync(p.MainWindowHandle, 1);
                Win32Util.SetForegroundWindow(p.MainWindowHandle);

                Environment.Exit(0);
            }
        }

        private static void ConfigureServices()
        {
            services = new ServiceCollection();

            services.AddScoped<AuthService>();
            services.AddScoped<PageService>();
            services.AddScoped<JsonFileService>();
            services.AddScoped<FileService>();
            services.AddScoped<ConnectionService>();
            services.AddScoped<CmdLogService>();
            services.AddTransient<SshService>();

            services.AddTransient<EditFileViewModel>();
            services.AddTransient<FileViewModel>();
            services.AddTransient<VariableViewModel>();
            services.AddTransient<FileMgrViewModel>();
            services.AddScoped<ConnectionViewModel>();
            services.AddTransient<CmdViewModel>();
            services.AddScoped<MainViewModel>();

            services.AddTransient<EditFileControl>();
            services.AddTransient<CmdPage>();
            services.AddTransient<FilePage>();

            serviceProvider = services.BuildServiceProvider();

            services.AddSingleton(serviceProvider);

            Ioc.Default.ConfigureServices(serviceProvider);
        }

        public static T GetService<T>() where T : class
        {
            return serviceProvider.GetService(typeof(T)) as T;
        }

        public static IServiceProvider GetProvider()
        {
            return serviceProvider;
        }
    }
}
